import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Ledger {


    private static final String FIRST_BLOCK = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";


    /**
     * 总的区块数量
     */
    private int blockCount;

    /**
     * 当前同步区块的index
     */
    private int current;




    public void genesisBlock(Wallet wallet, NetWork netWork) throws Exception {

        Block block = new Block();

        Transaction transaction = new Transaction();
        transaction.setInputs(null);

        Cost cost = new Cost();
        cost.setAddress(wallet.getAddress());
        cost.setAmount(50000000);
        transaction.setCosts(Arrays.asList(cost));
        transaction.setPtz(FIRST_BLOCK.getBytes());

        byte[] ser = transaction.serialize(wallet);
        byte[] hash = Hash256.hash(ser);

        transaction.setHash(hash);
        wallet.addToMyReceipt(hash, transaction);

        block.addTransaction(hash, transaction);

        List<TransactionId> transactionIdList = new ArrayList<>();
        transactionIdList.add(new TransactionId(hash));


        Header first = new Header();
        first.setHeight(0);
        first.setBits(24);
        first.setPreHash(new byte[32]);
        first.setTime(1659694515);
        first.setVersion(1);
        first.setMerkleRoot(Miner.buildMerkleRoot(transactionIdList));
        boolean result = Miner.mining(first);

        if (result) {
            block.setHeader(first);
            block.setTransactionIdList(transactionIdList);

            System.out.println("挖矿成功");

            byte[] hashId = Hash256.hash(Hash256.hash(first.serialize()));
            System.out.println(new BigInteger(hashId).toString());

            netWork.broadCastTransaction(ser);
            netWork.broadCastBlock(block);

            System.out.println("创世区块成功");
        }
    }


}
